<?php
/**
 * Created by PhpStorm.
 * user: yuki
 * Date: 2017/6/21
 * Time: 09:08
 */

namespace app\admin\controller;

use app\admin\model\Adminlog;
use app\common\controller\Commoncontroller;
use app\common\model\Feedback;
use app\common\model\User;
use think\Db;
use think\Request;
use app\admin\model\Base;
use app\admin\model\Menu;
use app\admin\model\Role;
use app\admin\model\Admin;
use app\common\model\Patientcase;
use app\common\model\Doctordepartment;
use app\common\model\Doctor;
use app\common\model\Patient;
use app\common\model\Article;

class Basecontroller extends Commoncontroller
{

    public function _initialize(){

        parent::_initialize();

        // 提交数据会通过闭包函数加载
        $this->adminLog = [
            //控制器名称
            'authority' => [
                //model名称
                'menu'=>[
                    //action
                    'action' => ['menu','addmenu','deletemenu','editmenu'],
                    //后台取消之后的跳转路径
                    'cancel_list' => 'menu',
                    //model名称
                    'model' => 'Menu',
                    //数据操作的函数
                    'func' =>   function($data,$userId,$admin_type){
                        $model = new Menu;
                      // menu 数据操作完成后,跳转的路径  $data:form/或其他的数据 $userId 当前登录者 $admin_type :操作人后台还是医生 1后台 2医生
                        $result =  $model::getMenuAdminLog('menu',$data,$userId,$admin_type);
                        return $result;
                    },

                ],
                'role'=>[
                    'action' => ['rolelist','addrole','editrole','deleterole'],
                    'cancel_list' => 'rolelist',
                    'model' => 'Role',
                    'func' =>  function($data,$userId,$admin_type){
                        $model = new Role;
                        $result =  $model::addRoleAdminLog('rolelist',$data,$userId,$admin_type);
                        return $result;
                    },
                ],
                'admin' =>[
                    'action' => ['admin_list','add_admin','edit_admin','del_admin'],
                    'cancel_list' => 'admin_list',
                    'model' => 'Admin',
                    'func' =>  function($data,$userId,$admin_type){
                        $model = new Admin;
                        $result =  $model::addAdminAdminLog('admin_list',$data,$userId,$admin_type);
                        return $result;
                    },

                    'validate' => true //是否有场景验证
                ],
                'doctordepartment'=>[
                    'action' => ['department','add_department','edit_department','del_department'],
                    'cancel_list' => 'department',
                    'model' => 'Doctordepartment',
                    'func' =>  function($data,$userId,$admin_type){
                        $model = new Doctordepartment;
                        $result =  $model::addDoctordepartmentAdminLog('department',$data,$userId,$admin_type);
                        return $result;
                    },
                ],

            ],
            'doctor' => [
            'doctor'=>[
                'action' => ['index','add_doctor','edit_doctor','del_doctor'],
                'cancel_list' => 'index',
                'model' => 'Doctor',
                'func' =>  function($data,$userId,$admin_type){
                    $model = new Doctor;
                    $result =  $model::addDoctorAdminLog('index',$data,$userId,$admin_type);
                    return $result;
                },
                'validate' => true //是否有场景验证
            ],
            ],
            'patient' => [
                'patient'=>[
                    'action' => ['edit_patient','del_patient'],
                    'cancel_list' => 'index',
                    'model' => 'Patient',
                    'func' =>  function($data,$userId,$admin_type){
                        $model = new Patient;
                        $result =  $model::getPatientAdminLog('index',$data,$userId,$admin_type);
                        return $result;
                    },
                ],
            ],
            'record' => [
                'patientcase'=>[
                    'action' => ['add_record','edit_record','del_record'],
                    'cancel_list' => 'index',
                    'model' => 'Patientcase',
                    'func' =>   function($data,$userId,$admin_type){
                        $model = new Patientcase;
                        $result =  $model::getPatientCaseAdminLog('index',$data,$userId,$admin_type);
                        return $result;
                    },

                ],
            ],

            'wx' => [
                'feedback'=>[
                    'action' => ['notes','notes_detail'],
                    'cancel_list' => 'notes',
                    'model' => 'Feedback',
                    'func' =>  function($data,$userId,$admin_type){
                        $model = new Feedback;
                        $result =  $model::getFeedbackAdminLog('notes',$data,$userId,$admin_type);
                        return $result;
                    },
                ],

            ],

            'log' => [
                'adminlog'=>[
                    'action' => ['index','del_log'],
                    'cancel_list' => 'index',
                    'model' => 'adminlog',
                    'func' =>  function($data,$userId,$admin_type){
                        $model = new Adminlog;
                        $result =  $model::getAdminLog('index',$data,$userId,$admin_type);
                        return $result;
                    },
                ],
            ],

        ];


        $this->isSendMsg = [
            'wx' => [
                'user'=>[
                    'action' => ['send_msg'],
                    'model' => 'user',
                    'msg_type' => 'tpl1',
                    'func' =>   function($record_id){
                        $model = new User;
                        $result =  $model::sendMsgToUser($record_id);
                        return $result;
                    },

                ],
            ]
        ];




    }

    public function __construct()
    {
        parent::__construct();
        $breadcrumbUrl = '';
        $breadcrumb = '欢迎页';
        $this->assign('breadcrumbUrl',$breadcrumbUrl);
        $this->assign('breadcrumb',$breadcrumb);

        // 解决跨域问题
        header("Access-Control-Allow-Origin:*");
       // session("ytuid",1);

        // session空值返回登录页
        if(empty(session("adminuid")))
        {
            $this->redirect("login/index");
        }

        $this->userId = session("adminuid");
        $this->assign('userId', $this->userId);
        $this->roleid = session("roleid");

        $adminName = session('admin_name');
        $this->assign('adminName', $adminName);

        $avatar = session('avatar');
        $this->assign('avatar', $avatar);

        //添加log日志+数据
        $data = $this->request->param();
       // print_r($data);
        $admin_type = 1;
        $this->addAdminLog($data,$admin_type);

//var_dump($this->request);

        // 根据权限获取功能列表
        $result = $this->getrolemenulist();
        //print_r($result);
        //exit;
        $this->assign('left_menu',$result);

        $controllerName = strtolower(CONTROLLER_NAME);
        $actionName = strtolower(ACTION_NAME);
        //获取路径
        //获取该登录人员的权限
        $this->path = $controllerName.'/'.$actionName;
         //  print_r($this->userId);
        if($this->path != 'index/index' && $this->userId  != '1' ){
           $getPermissionArr =  $this->getPermissionPath($this->path);
           //print_r($getPermissionArr);
            $this->assign('getPermissionArr',json_encode($getPermissionArr));
        }

        $this->assign('url',$this->request->action());
        $this->assign('pageurl',$this->request->url());

    }

    /**
     *获取访问的权限和路径
     *
    **/
    protected function getPermissionPath($path){
        try
        {
            //根据当前的操作获取其相关权限
            //获取当前的路径

            if(!$this->checkPermission($path)){
                return $this->error('当前暂无权限',url('index/index'));
            }

            //获取其在authority_menu 下面的子目录
            //合并是否有权限
            $topMenuId = DB::name('authority_menu')->field('id,upmenuid')->where("menuurl='{$path}'")->find();
           /* print_r(DB::name('authority_menu')->getLastSql());
            print_r($topMenuId);
            exit;*/
           // print_r($topMenuId);
            $roleid = session('roleid');
            $secondPermissionMenus = DB::name('authority_menu')
                    ->field('authority_menu.menuurl')
                    ->join('authority_rolemenu','authority_rolemenu.menuid=authority_menu.id')
                    ->where("(authority_menu.upmenuid={$topMenuId['id']} or authority_menu.upmenuid={$topMenuId['upmenuid']}) and authority_rolemenu.roleid={$roleid}")
                    ->select();

          //  print_r(DB::name('authority_menu')->getLastSql());
            return $secondPermissionMenus;

        }catch (Exception $e)
        {


            return $e->getMessage();
        }
    }


    /**
     * 获取该人员是否被授权获取该路径权限
     * @param $path 访问的路径
     * @param  return true或false;
     **/

    protected function checkPermission($path){

        try{


            $isPermission = DB::name('authority_menu')
                ->field('authority_menu.id')
                ->join('authority_rolemenu','authority_rolemenu.menuid=authority_menu.id')
                ->where("authority_rolemenu.roleid={$this->roleid} and authority_menu.menuurl='{$path}'")
                ->find();
            if($isPermission){
                return true;
            }else{
                return false;
            }


          }catch (Exception $e)
            {


            return $e->getMessage();
            }
    }




    /**
     * 添加记录日志问题
    **/
    protected function addAdminLog($data,$admin_type){
        //获取当前的路径
        $controllerName = strtolower(CONTROLLER_NAME);
        $actionName = strtolower(ACTION_NAME);

        $arr_log = $this->checkAdminLog($controllerName,$actionName,$this->adminLog);

        $path_url = CONTROLLER_NAME."/".$arr_log['cancel_list'];
        $this->assign('cancel_url',$path_url);

        //验证当前路径是否在数组中,则记录数据
        if($arr_log){

            if($this->request->post()){
                $scene = '';
                if(isset($arr_log['validate']) && $arr_log['validate']){

                    $scene = $actionName;
                }


                $result = $this->validate($data,$arr_log['model'].'.'.$scene);

                if(true !== $result){
                    // 验证失败 输出错误信息
                    return ['flag'=>'error','msg'=>$this->error($result),'url'=>''];
                }
            }

            //使用闭包函数
            $result  =  $arr_log['func']($data,$this->userId,$admin_type);
            $url = '';
            if(isset($result['url'])){
                $url = url($result['url']);
            }

            $record_id = '';
            if(isset($result['record_id'])){
                $record_id = $result['record_id'];
            }
//            var_dump($result);
           if($result['flag'] == 'success'){

               //验证是否要发送短信+短信之后的回复情况
               $this->checkSendMsg($controllerName,$actionName,$record_id,$this->isSendMsg);

                $this->success($result['msg'],$url);
            }else if($result['flag'] == 'error'){
                $this->error($result['msg'],$url);
            }else{

            }

        }
    }






    /**
     * 需要登录都变为小写
     */
    protected function arrayToLower($arr)
    {
        $item = array_map(function($data){
            if (is_array($data)) {
                foreach ($data as $key => &$item) {
                    if (is_array($item)) {
                        foreach ($item as $key => &$item) {
                            $item = strtolower($item);
                        }
                    }else{
                        $item = strtolower($item);
                    }
                }
            } else {
                $data = strtolower($data);
            }

            return $data;
        }, $arr);

        return $item;
    }



    // 根据权限获取功能列表
    public function getrolemenulist(){

        // 查询权限可以看到的功能列表
        if(session("adminuid") == 1){

            $rolemenulist = Db::query("select * from   authority_menu   WHERE authority_menu.`state` = '1' and authority_menu.`level` = '1' order by authority_menu.upmenuid,authority_menu.upmenuid,authority_menu.level asc ");
            foreach($rolemenulist as $key=>$val){

                $result_second = Db::query("select * from   authority_menu  WHERE authority_menu.`state` = '1' AND authority_menu.`upmenuid` = ?   order by authority_menu.upmenuid,authority_menu.upmenuid,authority_menu.level asc ",[$val['id']]);
                $rolemenulist[$key]['second'] = $result_second;
            }
        }else{
            $sql = "select * from authority_rolemenu INNER JOIN authority_menu ON authority_menu.id = authority_rolemenu.menuid WHERE authority_menu.`state` = '1'  AND authority_rolemenu.roleid = ? and authority_menu.level=1  order by sortlevel,authority_menu.level asc ";
            $rolemenulist = Db::query($sql,[session("roleid")]);
            //  print_r(Db::name('authority_rolemenu')->getLastSql());
            foreach($rolemenulist as $key=>$val){

                $sql = "select * from authority_rolemenu INNER JOIN authority_menu ON authority_menu.id = authority_rolemenu.menuid WHERE authority_menu.`state` = '1'  AND authority_menu.`upmenuid` = ? and  authority_rolemenu.roleid = ?   order by sortlevel,authority_menu.level asc ";

                $result_second = Db::query($sql,[$val['id'],session("roleid")]);
                //  print_r(Db::name('authority_rolemenu')->getLastSql());
                $rolemenulist[$key]['second'] = $result_second;
            }
        }

        //print_r(Db::name("authority_rolemenu")->getLastSql());
        return $rolemenulist;
    }


    /**
     * 获取全部数据
     * @param  string $type  tree获取树形结构 level获取层级结构
     * @param  string $order 排序方式
     * @return array         结构数据
     */
    public function getTreeData($data,$type='tree',$name='menuname',$child='id',$parent='upmenuid'){

        require_once  EXTEND_PATH."/Nx/Data.class.php";

        // 获取树形或者结构数据
        if($type=='tree'){
            $data= \Data::tree($data,$name,$child,$parent);
        }elseif($type="level"){
            $data= \Data::channelLevel($data,0,'&nbsp;',$child,$parent);
        }
        return $data;
    }





}
